<template>
  <main>
    <el-dialog :visible="editVis" @close="handleClose" title="修改用户" width="600px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px">
        <div v-for="item in formColumns" :key="item.props">
          <el-form-item :prop="item.props" :label="item.label">
            <!-- 下拉框 -->
            <el-select size="mini" v-if="item.ele === 'select'" clearable v-model="formData[item.props]" style="width: 80%">
              <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value">{{
                it.label
              }}</el-option>
            </el-select>
            <!-- input框 -->
            <el-input
              size="mini"
              v-if="item.ele === 'input'"
              v-model="formData[item.props]"
              style="width: 80%"
              placeholder="请输入"
              clearable
            ></el-input>
            <!-- 💭企查查 -->
            <div v-if="item.ele === 'qichachaItem'">
              <el-input
                v-if="inputType"
                size="mini"
                v-model="formData.sponsorName"
                placeholder="请输入关键字"
                style="width: 80%"
              ></el-input>
              <el-select
                v-else
                filterable
                v-model="formData.sponsorName"
                placeholder="请选择"
                clearable
                style="width: 80%"
              >
                <el-option v-for="item in optionsList" :key="item.Name" :label="item.Name" :value="item.Name">
                </el-option>
              </el-select>
              <el-button v-if="inputType" size="mini" type="primary" @click="handleGetOptions" style="margin-left: 4px"
                >查询</el-button
              >
              <el-button v-else size="mini" type="primary" @click="handleReset">重置</el-button>
              <p class="search-tips" style="font-size: 10px; line-height: 16px; margin-top: 4px">
                为保证数据的搜索效率，每次查询只返回五条选择项，请您尽可能多输入一些关键字。
              </p>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handleConfirm">确认</el-button>
        <el-button size="mini" @click="handleCancel">取消</el-button>
      </span>
    </el-dialog>
  </main>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  props: {
    editVis: {
      type: Boolean,
      default: false,
    },
    editDataProp: {
      type: Object,
    },
  },
  data() {
    return {
      // 表单规则
      formColumns: [
        { ele: 'input', props: 'nickName', label: '姓名：' },
        { ele: 'input', props: 'mobile', label: '手机号：' },
        { ele: 'select', props: 'roleId', label: '角色：', options: [] },
        { ele: 'input', props: 'email', label: '邮箱：' },
        { ele: 'qichachaItem', props: 'orgName', label: '单位：' },
      ],
      // 表单数据
      formData: {
        type: 0,
        roleIds: [],
        roleId: '',
        email: '',
        orgName: '',
        nickName: '',
        mobile: '',
        sponsorName: '',
      },
      // 表单校验
      formRules: {
        // roleId: [{ required: true, message: '请选择', trigger: 'blur' }],
        email: [{ validator: this.validatorTable, trigger: 'blur' }],
        mobile: [{ validator: this.validatorPhone, trigger: 'blur' }],
        orgName: [{ validator: this.validatorSponsorName, trigger: 'blur' }],
      },
      // 💭企查查
      inputType: true,
      optionsList: [],
    }
  },
  watch: {
    editDataProp(newV, oldV) {
      if (newV.roleList.length === 0) {
        this.formData.type = 1
        this.formData.roleIds = []
        this.formData.roleId = ''
      }
      newV.roleList.forEach(item => {
        this.formData.roleIds.push(item.id)
        this.formData.roleId = item.id
      })
      this.formData.orgName = newV.orgName
      this.formData.sponsorName = newV.orgName
      this.formData.nickName = newV.nickname
      this.formData.mobile = newV.mobile
      this.formData.id = newV.id
      this.formData.email = newV.email
      this.handleGetOptions('editFirst')
      if (newV) {
        this.getRolesName()
      }
    },
  },

  methods: {
    ...mapActions('usersManage', ['getRolesNameAPI']),
    ...mapActions('projectList', ['qryProviderNameByName']),
    // 💭企查查
    // 重置
    handleReset() {
      this.inputType = true
      this.formData.sponsorName = ''
    },
    // 查询企业下拉项
    handleGetOptions(string) {
      if (!this.formData.sponsorName) {
        if (string !== 'editFirst') {
          this.$message.error('请输入关键字查询~')
        }
        return
      }

      this.inputType = false
      const data = {
        searchName: this.formData.sponsorName,
      }
      this.qryProviderNameByName({ data }).then(res => {
        const { code, data = [] } = res
        if (code === 200) {
          const result = JSON.parse(data)
          this.optionsList = result.Result.Data || []
        }
      })
    },
    // 校验邮箱格式是否正确
    validatorTable(rule, userList, callback) {
      const emailRule =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      const flag = userList.match(emailRule)
      if (flag) {
        callback()
      } else {
        callback(new Error('邮箱格式不正确！'))
      }
    },
    // 校验手机号格式是否正确
    validatorPhone(rule, userList, callback) {
      const phoneRule = /^1[3-9]\d{9}$/
      const flag = userList.match(phoneRule)
      if (flag) {
        callback()
      } else {
        callback(new Error('手机号格式不正确！'))
      }
    },
    // 校验单位
    validatorSponsorName(rule, userList, callback) {
      if (this.optionsList.length === 0) {
        callback(new Error('请正确选择单位！'))
      } else {
        if (!this.optionsList.find(item => item.Name === this.formData.sponsorName)) {
          callback(new Error('请选择正确单位！'))
        } else {
          callback()
        }
      }
    },
    handleClose() {
      this.publicClose()
    },
    // 公共关闭
    publicClose() {
      this.$refs.formRef.resetFields()
      this.formData.roleIds = []
      this.formData.roleId = ''
      this.$emit('update:editVis', false)
    },
    async handleConfirm() {
      this.formData.roleIds = [this.formData.roleId]
      const data = {
        ...this.formData,
        userList: [
          {
            id: this.formData.id,
            nickname: this.formData.nickName,
            mobile: this.formData.mobile,
            email: this.formData.email,
          },
        ],
      }
      await this.$refs.formRef.validate()
      data.userList[0].orgName = data.sponsorName
      this.$emit('updateUserData', data)
    },
    handleCancel() {
      this.publicClose()
    },
    // 获取下拉框选项
    getRolesName() {
      const params = {
        type: '0',
      }
      this.getRolesNameAPI({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.formColumns[2].options = data.records.map(item => {
            return {
              label: item.name + '(' + item.code + ')',
              value: item.id,
            }
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
